import json

from flask import Flask, jsonify
from faker import Faker
import os
import random
# from mock.CustomProvider import CustomProvider
import datetime

from faker.providers import BaseProvider
import random


# 创建自定义的数据供应商
class CustomProvider(BaseProvider):
    @staticmethod
    # # 通过random.randint(a, b)方法得到随机数字
    def generate_random_str(length):
        random_str = ""
        base_str = "ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789"
        n = len(base_str) - 1
        for i in range(length):
            random_str += base_str[random.randint(0, n)]
        return random_str

    @staticmethod
    # # 返回index 1
    def generate_count():
        msg_count = [1, 2, 3]
        return random.choice(msg_count)

    @staticmethod
    # # 返回index 1
    def generate_index1():
        return 1

    @staticmethod
    # 返回type 类型，sms：短信，mms：彩信，vms：视频短信
    def generate_msg_type():
        msg_type = ['sms', 'mms', 'vms']
        return random.choice(msg_type)

    @staticmethod
    # 返回type 类型，sms：短信，mms：彩信，vms：视频短信
    def generate_msg_status():
        status_type = ['0']
        return random.choice(status_type)


# 设定faker文化语种，可更改en_US等，此处默认中文
faker = Faker(locale='zh_CN')
# 添加自定义数据供应商到faker 库
faker.add_provider(CustomProvider)

app = Flask(__name__)


# 写入 TXT 文件
def write_to_file(f_path, content):
    with open(f_path, 'a') as file:
        if isinstance(str(content), str):
            file.write(str(content) + '\n')
        elif isinstance(str(content), list):
            file.writelines(str(content) + '\n')


def get_last_line(f_path):
    # 以只读的方式打开文件
    with open(f_path, 'r') as f:
        if f.mode == 'r':
            # 读取到最后一行
            last_line = f.readlines()[-1]
            return last_line
        else:
            print("文件无法打开或不存在")


def get_file_line_count(f_path):
    # 初始化计数器，用于记录行数
    line_count = 0
    with open(f_path, 'r') as file:
        # 逐行读取文件内容
        for _ in file:
            line_count += 1
    return line_count


# 读取 TXT 文件
def read_file(f_path):
    with open(f_path, 'r', encoding='utf-8') as file:
        data = file.readlines()
        return data


class Msg:
    def __init__(self, str_data, msg_id, count, index, msg_status):
        data_list = str_data.split(',')
        self.type = data_list[0]
        self.msgId = msg_id
        self.mobile = data_list[2]
        self.count = count
        self.index = index
        self.status = msg_status
        self.reportTime = data_list[6]
        # 定义 to_dict 方法，将类对象的属性转换为字典

    def to_dict(self):
        return {
            "type": self.type,
            "msgId": self.msgId,
            "mobile": self.mobile,
            "count": int(self.count),
            "index": int(self.index),
            "status": self.status,
            "reportTime": self.reportTime,
        }


# 获取当前工作目录
pwd = os.getcwd()
file_path = pwd + "\\test.txt"
record_path = pwd + "\\record.txt"


@app.route('/', methods=['GET'])
def hello():
    # 每次读取行数
    nums = 101
    # 获取msg_id总量级
    line_count = get_file_line_count(file_path)
    print("文件总行数：" + str(line_count))

    # 获取已查询行数记录
    before_line = int(get_last_line(record_path))
    print("已读取行数：" + str(before_line))

    # 文件读取结束处理
    last_count = nums + before_line
    if last_count > line_count:
        last_count = line_count
        nums = line_count - before_line

    # 写入本次读取后行数
    write_to_file(record_path, last_count)

    # 构造data
    result = []
    file_list = read_file(file_path)

    # 截取当前批次数据
    msg_id_list = file_list[before_line:last_count]

    while nums > 0:
        for line in msg_id_list:
            # 截断 仅获取目标数量
            if nums == 0:
                break
            msg_id_str = line.strip()

            data_rule = "str(faker.generate_msg_type())+','+str(random.randint(1000000,9999999))+'," \
                        "'+str(faker.phone_number(" \
                        "))+','+str(faker.generate_count())+','+str(faker.generate_index1())+'," \
                        "'+str(faker.generate_msg_status())+','+str(faker.date_time_between(datetime.datetime.now() + " \
                        "datetime.timedelta(weeks=-1), datetime.datetime.now()).strftime('%Y-%m-%d %H:%M:%S')) "
            data_str = eval(data_rule)
            # 取出真实msg_id
            msg_id = str(msg_id_str.split(',')[0])
            count = int(data_str.split(',')[3])
            index = int(data_str.split(',')[4])
            msg_type = str(data_str.split(',')[0])
            msg_status = str(data_str.split(',')[5])
            if msg_type == 'sms':
                msg_status = 'DELIVRD'
            if count > 1 & index < count:
                for index in range(count):
                    count = count
                    index = index + 1
                    # print(data_str)
                    data_row = Msg(data_str, msg_id, count, index, msg_status)
                    data_s = json.loads(json.dumps(data_row.to_dict()))
                    result.append(data_s)
                    nums = nums - 1
                    if nums == 0:
                        break
            else:
                # print(data_str)
                data_row = Msg(data_str, msg_id, count, index, msg_status)
                data_s = json.loads(json.dumps(data_row.to_dict()))
                result.append(data_s)
                nums = nums - 1
                if nums == 0:
                    break

    file_data = {
        "code": 1,
        "msg": "success!",
        "data": result
    }

    if before_line == line_count:
        write_to_file(record_path, 0)
    return jsonify(file_data)


if __name__ == '__main__':
    app.run(port=8888, debug=True, host='0.0.0.0')
